<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use onekey\Email;
use think\facade\View;
use think\facade\Cache;
use think\exception\ValidateException;
use app\admin\BaseController;
use app\admin\model\Admin as AdminModel;
use app\admin\validate\Admin as AdminValidate;
/**
 * 管理员登录、修改密码
 */
class Login  extends BaseController
{
    /**
     * 登录
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $input = input('post.');
            $locks = 5; // 最多尝试5次防止暴力破解
            $error = cache('admin-login'.$this->request->ip());
            $error = empty($error) ? 0 : $error;
            if ($locks - $error == 0) {
                return json(['status' => 'error', 'message' => '您的账号被锁定，请1小时后再试或联系管理员！']);
            }
            try {
                validate(AdminValidate::class)->scene('login')->check($input);
            } catch ( ValidateException $e ) {
                return json(['status' => 'error', 'message' => $e->getError()]);
            }
            $userInfo = AdminModel::with(['group'])->where('account|email',$input['account'])->find();
            if (! $userInfo) {
                cache('admin-login'.$this->request->ip(), $error + 1 ,3600);
                return json(['status' => 'error', 'message' => '密码或账号错误，您还有'.($locks - $error).'次机会']);
            }
            $password = AdminModel::where('id', $userInfo->id)->value('password');
            if (! password_verify($input['password'], $password)) {
                cache('admin-login'.$this->request->ip(), $error + 1 ,3600);
                return json(['status' => 'error', 'message' => '密码或账号错误，您还有'.($locks - $error).'次机会']);
            }
            if ($userInfo->status != 1) { 
                return json(['status' => 'error', 'message' => '您的账号被屏蔽']);
            }
            // 修改信息
            $userInfo->login_count = $userInfo->login_count + 1;
            $userInfo->login_ip    = $this->request->ip();
            $userInfo->login_time  = date('Y-m-d H:i:s');
            $userInfo->save();
            session('admin', $userInfo);
            return json(['status' => 'success', 'message' => '登录成功']);
        } else {
            session('admin',null);
            return View::fetch();
        }
    }

    /**
     * 修改密码
     */
    public function passwordEmail()
    {
        if ($this->request->isPost()) {
            try {
                $input = input('post.');
                validate(AdminValidate::class)->scene('password')->check($input);
            } catch ( ValidateException $e ) {
                return json(['status' => 'error', 'message' => $e->getError()]);
            }
            if ($input['code'] !== cache('password_email_code' . $input['email'])) {
                return json(["status" => "error", "message" => '验证码不正确']);
            }
            $save = AdminModel::where('email', $input['email'])->find();
            if (! $save) {
                return json(['status' => 'error', 'message' => '账号不存在']);
            }
            $save->password = $input['password'];
            $save->save();
            return json(['status' => 'success', 'message' => '修改成功']);
        } else {
            return View::fetch();
        }
    }

    /**
     * 发送修改密码邮箱验证码
     */
    public function sendPasswordEmailCode()
    {
        if ($this->request->isPost()) {
            try {
                $input = input('post.');
                validate(AdminValidate::class)->scene('code')->check($input);
            } catch ( ValidateException $e ) {
                return json(['status' => 'error', 'message' => $e->getError()]);
            }
            if (AdminModel::where('email', $input['email'])->value('id')) {
                $email  = $input['email'];
                $name   = 'password_email_code';
                $operation = '修改密码';
                $title = '验证码';
                $code  = rand(1000,9999);
                $body  = $operation . "验证码<br/>您好" . $email . "!<br/>" . $title . "，请将验证码" . $operation . "页面。<br/>验证码：" . $code . "";
                $result = Email::send($email, $title, $body);
                if ($result['status'] === 'success') {
                    Cache::set($name.$email, $code, 300);
                    return json(['status' => 'success','message' => '获取成功']);
                } else {
                    return json($result);
                }
            } else {
                return json(['status' => 'error', 'message' => '邮箱号未注册']);
            }
        }
    }
}
